//
//  WQUserAccountViewModel.swift
//  WeiBo
//
//  Created by 张德华 on 7/27/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import UIKit

class WQUserAccountViewModel: NSObject {
    
    let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archiver")
    
    /**全局访问点*/
    static let sharedTools: WQUserAccountViewModel = WQUserAccountViewModel()
    
    /**模型属性*/
    var userAccountModel: WQUserAccountModel?
    
    
    var accessToken: String? {
        
        // TODO: -
//        /------ 代表用户有accessToken
        if userAccountModel?.access_token != nil {
            if userAccountModel?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return userAccountModel?.access_token
            } else {
                ///------ 过期
                return nil
            }
        } else {
            ///------ 没有token,用户没有登录或没有保存数据
            return nil
        }
    }
    
    ///------ 判断用户是否登录
    var isLogin: Bool {
        return accessToken != nil
    }
    
    override init() {
        super.init()
        userAccountModel = getUserAccount()
    }
}

// MARK: - ************归档解档
extension WQUserAccountViewModel {
    
    // MARK: - ************保存对象
    func saveUserAccount(userAccount: WQUserAccountModel) {
         self.userAccountModel = userAccount
        
        
        NSKeyedArchiver.archiveRootObject(userAccountModel!, toFile: file)
    }
    
    
    // MARK: - ************获取对象
    func getUserAccount() -> WQUserAccountModel? {
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? WQUserAccountModel
        return result
    }
}




// MARK: - ************请求数据
extension WQUserAccountViewModel {
    
    // MARK: - ************请求userAccount
    func loadUserAccount(code: String, isSuccess:(isSucc: Bool) -> ()) {
        WQNetworkTools.sharedManager.oauthLoadUserAccount(code) { (result) in
            
            guard let res = result else {
                isSuccess(isSucc: false)
                return
            }
            
            let userAccount = WQUserAccountModel(dict: res)
            self.loadUserInfo(userAccount, isSuccess: isSuccess)
        }
    }
    
    
    // MARK: - ************请求用户信息
    func loadUserInfo(userAccount: WQUserAccountModel, isSuccess: (isSucc: Bool) -> ()) {
        WQNetworkTools.sharedManager.oauthLoadUserInfo(userAccount) { (result) in
            
            guard let res = result else {
                isSuccess(isSucc: false)
                return
            }
            
            userAccount.screen_name = res["screen_name"] as? String
            userAccount.avatar_large = res["avatar_large"] as? String
            
            isSuccess(isSucc: true)
        }
        
        
        
        
        
    }
    
    
    
    
    
}